<template>
  <div class="log_bg">
    <div class="top">
      <div class="logo">
        <a href="" @click.prevent="toIndex"><img src="/images/logo.png" /></a>
      </div>
    </div>
    <div class="login">
      <div class="log_img">
        <img src="/images/l_img.png" width="611" height="425" />
      </div>
      <div class="log_c">
        <form @submit.prevent="save">
          <table border="0" style="width: 370px; font-size: 14px; margin-top: 30px" cellspacing="0" cellpadding="0">

            <tbody>
              <tr height="50" valign="top">
                <td width="55">&nbsp;</td>
                <td>
                  <span class="fl" style="font-size: 24px">登录</span>
                  <span class="fr">还没有商城账号，<a href="#" @click.prevent="toRegist" style="color: #ff4e00">立即注册</a></span>
                </td>
              </tr>
              <tr height="70">
                <td>用户名</td>
                <td>
                  <input type="text" v-model="user.loginname" class="l_user" :class="{ 'error': errors.loginname }" />
                  <span v-if="errors.loginname" class="error-text">{{ errors.loginname }}</span>
                </td>
              </tr>
              <tr height="70">
                <td>密&nbsp; &nbsp; 码</td>
                <td>
                  <input type="password" v-model="user.password" class="l_pwd" :class="{ 'error': errors.password }" />
                  <span v-if="errors.password" class="error-text">{{ errors.password }}</span>
                </td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <!-- <td style="font-size: 12px; padding-top: 20px">
                  <span style="font-family: '宋体'" class="fl">
                    勾选不再是必选，移除错误提示
                    <label class="r_rad"><input type="checkbox" v-model="isSaveLogin" /></label><label
                      class="r_txt">保存登录信息（下次免登录）</label>
                  </span>
                  <span class="fr"><a href="#" style="color: #ff4e00">忘记密码</a></span>
                </td> -->
              </tr>
              <tr height="60">
                <td>&nbsp;</td>
                <td>
                  <input type="submit" value="登录" class="log_btn" :disabled="isLoading" />
                </td>
              </tr>
            </tbody>
          </table>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref , onMounted , onUnmounted} from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

import store from '@/store'


const router = useRouter()

const user = ref({
  loginname: '',
  password: ''
})
const isSaveLogin = ref(false)
const errors = ref({})
const isLoading = ref(false)


const setShowPage = (val) => {
  store.commit('setShowPage', val)
}
// 首页
const toIndex = () => {

    router.push({ name: 'index' })
}


//注册
const toRegist = () => {
  router.push({ name: 'regist' })
}

const validateForm = () => {
  const newErrors = {}
  if (!user.value.loginname.trim()) {
    newErrors.loginname = '请输入用户名'
  }
  if (!user.value.password) {
    newErrors.password = '请输入密码'
  }
  errors.value = newErrors
  return Object.keys(newErrors).length === 0
}

const save = async () => {
  if (!validateForm()) {
    return
  }

  const response = await axios.post('/api/loginUser',{
    loginName: user.value.loginname,
    password: user.value.password
  })

    
  if (response.data.code === 5200) {
    alert('登录成功')
    
    console.log("111",response.data)
    const userData = response.data;
   

    if (userData) {
      // 保存用户信息到sessionStorage
      window.sessionStorage.setItem('token',userData.token)
      window.sessionStorage.setItem('id', userData.id)
  
      window.sessionStorage.setItem('userName', userData.userName)
      window.sessionStorage.setItem('loginName', userData.loginName || user.value.loginname)
      window.sessionStorage.setItem('type', userData.type)
    }

    console.log("用户信息:", userData);

    // 添加延迟确保sessionStorage更新完成
    setTimeout(() => {
      toIndex()
    }, 100)
  } else {
    alert(response.data.msg || '登录失败，请检查账号密码')
  }
}


     // 进入管理页面时隐藏HeaderView
    onMounted(() => {
        store.commit('setShowPage', 1)
    })
    
    // 离开管理页面时恢复HeaderView
    onUnmounted(() => {
        store.commit('setShowPage', 0)
    })

</script>

<style>
.error {
  border: 1px solid #ff4e00 !important;
}

.error-text {
  color: #ff4e00;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

.loading-text {
  margin-left: 10px;
  color: #666;
  font-size: 14px;
}
</style>